<?php


namespace App\Http\Controllers\WebApi\Business;


use App\Models\ImFriendsCircle;
use App\Models\ImFriendsCirclePraise;
use App\Models\ImUserFriend;
use App\Models\ImUsers;

class FriendsCircleBusiness
{

    public function praise($id, $friend_id)
    {
        //校验朋友圈ID
        $user_id = ImFriendsCircle::where('id', $id)->value('user_id');
        if (!$user_id) {
            return ['code' => 400, 'msg' => 'ID有误'];
        }
        //校验用户是否有效
        $userCount = ImUsers::where('id', $friend_id)->count();
        if (!$userCount) {
            return ['code' => 400, 'msg' => '用户信息有误'];
        }
        //校验是否为好友
        if (!$this->checkFriend($user_id, $friend_id)) {
            return ['code' => 400, 'msg' => '您没有点赞权限'];
        }
        //是否有点过赞
        $praise = ImFriendsCirclePraise::where('friend_id', $friend_id)->where('fc_id', $id)->first();
        $status = 1;
        if ($praise) {
            if ($praise->status == 1) {
                $status = 0;
            } else {
                $status = 1;
            }
        } else {
            $praise = new ImFriendsCirclePraise();
            $praise->friend_id = $friend_id;
            $praise->fc_id = $id;
        }
        //保存点赞记录
        $praise->status = $status;
        $praise->save();
        return ['code' => 0, 'msg' => 'ok'];
    }

    /**
     * 校验好友关系
     * @param $user_id
     * @param $friend_id
     * @return bool
     */
    public function checkFriend($user_id, $friend_id)
    {
        $friend = ImUserFriend::where('uid', $user_id)->where('other_uid', $friend_id)->first();
        if (!$friend) {
            return false;
        }
        return true;
    }
}
